package demo.yangxu.springboot.controller;

import demo.yangxu.springboot.dao.DepartmentDao;
import demo.yangxu.springboot.dao.EmployeeDao;
import demo.yangxu.springboot.entities.Department;
import demo.yangxu.springboot.entities.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;

@Controller
public class EmployeeController {

    @Autowired
    EmployeeDao employeeDao;

    @Autowired
    DepartmentDao departmentDao;

    //查询所有员工返回列表页面
    @GetMapping("/emps")
    public String list(Model model){
        Collection<Employee> employees = employeeDao.getAll();
        //放在请求域中
        model.addAttribute("emps",employees);
        // thymeleaf默认就会拼串
        // classpath:/templates/xxxx.html
        return "/emp/list";
    }
    //进入员工添加页面
    @GetMapping("/emp")
    public String toAddPage(Model model) {
        //查出所有的部门
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("depts",departments);
        //进入员工添加页面
        return "/emp/add";
    }

    //员工添加功能
    //SpringMVC自动将请求参数和入参对象的属性进行一一绑定；
    //要求请求参数的名字和javaBean入参的对象里面的属性名是一样的
    @PostMapping("/emp")
    public String addEmp(Employee employee){
        //保存员工信息
        employeeDao.save(employee);
        //添加完成后，进入员工列表
        // redirect: 表示重定向到一个地址  /代表当前项目路径
        // forward: 表示转发到一个地址
        return "redirect:/emps";
    }
    //进入修改页面，查出当前员工，在页面回显
    @GetMapping("/emp/{id}")
    public String toEditPage(@PathVariable("id") Integer id, Model model){
        Employee employee = employeeDao.get(id);
        model.addAttribute("emp",employee);
        //查出所有的部门
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("depts",departments);
        //进入修改页面(add是一个修改添加二合一的页面)
        return "emp/add";
    }

    //员工修改功能
    @PutMapping("/emp")
    public String updateEmployee(Employee employee){
        System.out.println("员工修改的数据："+employee);
        employeeDao.save(employee);
        return "redirect:/emps";
    }

    //员工删除功能
    @DeleteMapping("/emp/{id}")
    public String deleteEmployee(@PathVariable("id") Integer id){
        employeeDao.delete(id);
        return "redirect:/emps";
    }
}
